<template>
  <div class="account-container">
    <a-card class="box-card">
      <template #title>
        <span>用户登录</span>
      </template>

      <!-- 登录表单 -->
      <a-form :model="loginForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="私钥" required>
          <a-input v-model:value="loginForm.privateKey" placeholder="请输入私钥" />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 6 }">
          <a-button type="primary" @click="login">登录</a-button>
        </a-form-item>
      </a-form>

      <!-- 显示账户信息 -->
      <div v-if="accountInfo">
        <h3>账户信息</h3>
        <p>地址：{{ accountInfo.address }}</p>
        <p>私钥：{{ accountInfo.privateKey }}</p>
        <p>公钥：{{ accountInfo.publicKey }}</p>
      </div>

      <!-- 注册按钮 -->
      <div class="register-button">
        <a-button type="primary" @click="goToRegister">注册新用户</a-button>
      </div>

    </a-card>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import axios from 'axios'

export default {
  name: 'AccountLogin',
  data() {
    return {
      loginForm: {
        privateKey: ''
      },
      accountInfo: null
    }
  },
  methods: {
    async login() {
      try {
        if (!this.loginForm.privateKey) {
          message.warning('请输入私钥')
          return
        }
        // 存储私钥
        localStorage.setItem('privateKey', this.loginForm.privateKey)

        const response = await axios.post('/api/account/login', {
          privateKey: this.loginForm.privateKey
        })

        this.accountInfo = response.data
        message.success('登录成功,')
        // 登录成功后跳转到慈善页面
        this.$router.push('/charity')
      } catch (error) {
        message.error('登录失败：' + error.message)
      }
    },
    goToRegister() {
      this.$router.push('/accountRegister')
    }
  }
}
</script>

<style scoped>
.account-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.register-button {
  margin-top: 20px;
  text-align: center;
}
</style>